package com.css.zfzx.fxpg.modules.picture.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.fxpg.common.utils.ServerUtil;
import com.css.zfzx.fxpg.modules.picture.repository.FxPictureNativeRepository;
import com.css.zfzx.fxpg.modules.picture.repository.entity.FxPictureEntity;
import com.css.zfzx.fxpg.modules.picture.viewobjects.FxPictureQueryParams;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author leon
 * @date 2020-11-17
 */
@Repository
@PropertySource("classpath:platform-config.yml")
public class FxPictureNativeRepositoryImpl implements FxPictureNativeRepository {
    @PersistenceContext
    private EntityManager em;

    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;

    private static final Logger log = LoggerFactory.getLogger(FxPictureNativeRepositoryImpl.class);


    @Override
    public Page<FxPictureEntity> queryFxPictures(FxPictureQueryParams queryParams, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from fx_picture ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if (!PlatformObjectUtils.isEmpty(queryParams.getPictureName())) {
            whereSql.append(" and picture_name like :pictureName");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getPictureDescription())) {
            whereSql.append(" and picture_description like :pictureDescription");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCreateUser())) {
            whereSql.append(" and create_user like :createUser");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getType())) {
            whereSql.append(" and type = :type");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city = :city");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area = :area");
        }


        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        // 是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        // 是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        // 是否为区级管理员
        boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);

        if (!containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user =:user");
            }
            // 省级管理员
            if (containtRolePro) {
                whereSql.append(" and province like :divisionName");
            }
            // 市级管理员
            if (containtRoleCity) {
                whereSql.append(" and city like :divisionName");
            }
            // 区级管理员
            if (containtRoleArea) {
                whereSql.append(" and area like :divisionName");
            }
        }
        // 排序
        whereSql.append(" ORDER BY create_time desc");

        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), FxPictureEntity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from fx_picture ");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if (!PlatformObjectUtils.isEmpty(queryParams.getPictureName())) {
            query.setParameter("pictureName", "%" + queryParams.getPictureName() + "%");
            countQuery.setParameter("pictureName", "%" + queryParams.getPictureName() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getPictureDescription())) {
            query.setParameter("pictureDescription", "%" + queryParams.getPictureDescription() + "%");
            countQuery.setParameter("pictureDescription", "%" + queryParams.getPictureDescription() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCreateUser())) {
            query.setParameter("createUser", "%" + queryParams.getCreateUser() + "%");
            countQuery.setParameter("createUser", "%" + queryParams.getCreateUser() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getType())) {
            query.setParameter("type", queryParams.getType());
            countQuery.setParameter("type", queryParams.getType());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", queryParams.getProvince());
            countQuery.setParameter("province", queryParams.getProvince());

        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", queryParams.getCity());
            countQuery.setParameter("city", queryParams.getCity());

        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("area", queryParams.getArea());
            countQuery.setParameter("area", queryParams.getArea());
        }

        if (!containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                String user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId).getUserName();
                query.setParameter("user", user);
                countQuery.setParameter("user", user);
            }
            // 省级管理员 市级管理员 区级管理员
            if (containtRolePro || containtRoleCity || containtRoleArea) {
                // 获取部门地区名称
                String divisionName = ServerUtil.getDivisionEntity().getDivisionName();
                query.setParameter("divisionName", "%" + divisionName + "%");
                countQuery.setParameter("divisionName", "%" + divisionName + "%");
            }
        }


        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<FxPictureEntity> list = query.getResultList();
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Page<FxPictureEntity> fxPicturePage = new PageImpl<>(list, pageable, count.longValue());
        return fxPicturePage;
    }
}
